<script setup>
import  { tool }  from "../../tool/index"
import { ref, inject } from 'vue'
import { ElMessage } from 'element-plus'
// 初始化数据
const store = inject('store')
const user = ref(store.state.user)
const oldPassword = ref('')
const tempNewPassword = ref('')
const newPassword = ref('')
const passwordColumn = ["password"]
const idColumn = ["id"]
// 更改密码
async function changePassword() {
  try {
    
    const data={
        key: "Search",
        columns: passwordColumn,
        data: {
          key: idColumn,
          value: [user.value.id]
        }
      }
    const { data: [userData] } = await tool.axiosApi("user", data, "get")

    const compare = userData.password === oldPassword.value
    
    if (compare) {
      if (newPassword.value === tempNewPassword.value && newPassword.value !== null && tempNewPassword.value !== null) {
        const data = {
          key: "update",
          data: {
            key: passwordColumn,
            value: [tempNewPassword.value]
          },
          where: {
            key: idColumn,
            value: [user.value.id]
          }
        }
        const { message } = await tool.axiosApi("user", data, "post")
        if (message === true) {
          ElMessage({
            type: "success",
            message: "密码更改成功"
          })
        } else {
          ElMessage({
            type: "error",
            message: "密码更改失败"
          })
        }
      } else {
        ElMessage("两次新密码不匹配，且不能为空，请检查")
      }
    } else {
      ElMessage("旧密码输入错误，请重新输入")
    }
  } catch (error) {
    ElMessage.error('发生错误，请重试')
  }
}
</script>

<template>
<div class="from" >
    <el-form>
    <el-form-item label="请输入旧密码">
      <el-input type="password" show-password v-model="oldPassword" />
    </el-form-item>
    <el-form-item label="请输入新密码">
      <el-input  type="password" show-password v-model="newPassword" />
    </el-form-item>
    <el-form-item label="请确认新密码">
      <el-input  type="password" show-password v-model="tempNewPassword" />
    </el-form-item>
  </el-form>
  <div class="sub" >
    <el-button  @click="changePassword()" type="primary">确认修改</el-button>
  </div>
</div>

</template>
<style scoped>
.from{
    margin: auto;
    width: 500px;
}
.sub{
    text-align: right;
}
</style>
